// 全局请求路径，也就是后端的请求基准路径
import { baseApi } from "@/config.js";
// 同时发送异步代码的次数，防止一次点击中有多次请求，用于处理
let ajaxTimes = 0;
const defaultHeader = {
	'content-type': 'application/json;charset=UTF-8',
	withCredentials: true,
	crossDomain: true
}

// 封装请求方法，并向外暴露该方法
const myHttp = (options) => {
	// 解构请求头参数
	let header = {};
	if (options.header) {
		header = { ...defaultHeader,
			...options.header
		};
	}
	// console.log(options.header);
	const isToken = (options.header || {}).isToken === false;
	let token = uni.getStorageSync('token')
	if (token && !isToken) {
		header['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义token 请根据实际情况自行修改
	}
	if (ajaxTimes == 0 && !options.hideLoad) {
		// NProgress.start()
		uni.showLoading({
			title: "加载中",
			mask: true,
		});
	}
	ajaxTimes++;
	// 显示加载中 效果
	// console.log("ajaxTimes------",ajaxTimes)

	return new Promise((resolve, reject) => {
		uni.request({
			url: baseApi + options.url,
			method: options.method || 'get',
			data: options.data || options.params || {},
			header,
			success: (res) => {
				console.log(res)
				uni.stopPullDownRefresh()
				// console.log(res.data)
				// console.log("routes==",routePath);
				switch (res.data.code) {
					case 401:
						uni.showToast({
							title: '登录失效，请重新登录',
							icon: 'none',
							duration: 2000
						});
						
						uni.removeStorageSync('token');
						let routes = getCurrentPages();
						let routePath = routes.length>0&&routes[0].route;
						let loginPath="/pages/login/index";
						
						if(routePath!=loginPath){
							uni.reLaunch({
								url: loginPath,
							})
						}
						
						break
					case 403:
						console.log("进入了403")
						uni.removeStorageSync("token")
						uni.showToast({
							title: res && res.data.msg || '拒绝访问',
							icon: 'none',
							duration: 4000
						});
						break
					case 404:
						uni.showToast({
							title: res && res.data.msg || '很抱歉，资源未找到!',
							icon: 'none',
							duration: 4000
						});
						break
					case 500:
						uni.showToast({
							title: res && res.data.msg || '服务器错误',
							icon: 'none',
							duration: 2000
						});
						break;
					case 502:
						uni.showToast({
							title: res && res.data.msg || '服务器异常',
							icon: 'none',
							duration: 2000
						});
						break;
				}
				resolve(res.data)
			},
			fail: (error) => {
				setTimeout(function() {
					// console.log(error)
					uni.showToast({
						title: error && error.msg || '网络繁忙，请稍后再试',
						icon: 'none',
						duration: 2000
					});
				}, 100)
				reject(error)
			},
			// 完成之后关闭加载效果
			complete: () => {
				ajaxTimes--;
				// console.log("ajaxTimes======>>",ajaxTimes)
				if (ajaxTimes === 0 && !options.hideLoad) {
					//  关闭正在等待的图标
					uni.hideLoading();
				}
			}
		})
	})
}
export default myHttp;

/**
 * 上传文件
 * @param {Object} tempFilePath uni文件路径
 */
export function saveFile(tempFilePath) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseApi + "file",
			header: {
				'Authorization': 'Bearer ' + uni.getStorageSync('token'),
			},
			filePath: newFillPath,
			name: 'file',
			success: (uploadFileRes) => {
				if (uploadFileRes.statusCode == 200) {
					let resData = JSON.parse(uploadFileRes.data)
					resolve(resData)
				} else {
					reject(err)
				}
			},
			fail: (err) => {
				reject(err)
			}
		});
	})
};
